package k6_exam;

import java.util.Random;

/**
 * 设计两个个线程模拟存取款操作
 * 其中一个线程每次随机存1~1000元钱，另外一个线程取1－1000元钱
 * 如果余额不足，则取款失败，提示余额不足
 * 写出程序（考虑并发问题）
 */
public class Account {

    private int money = 1000;

    /**
     * 存钱
     * @param money
     */
    public synchronized void saveMoney(int money){
        this.money+=money;
        System.out.println("成功存款"+money+"元,现有余额："+this.money);
    }

    /**
     * 取钱
     * @param money
     */
    public synchronized void takeMoney(int money){
        if(money<=this.money){
            this.money-=money;
            System.out.printf("成功取款%d元,现有余额：%d \n",money,this.money);
        }else{
            System.out.println("余额不足");
        }
    }

}

class Test{
    public static void main(String[] args) {

        Random random = new Random();
        Account account = new Account();

        new Thread(()->{
            while(true){
                try {
                    account.saveMoney(random.nextInt(1000)+1);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
        new Thread(()->{
            while(true){
                try {
                    account.takeMoney(random.nextInt(1000)+1);
                    Thread.sleep(700);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
